home *** CD-ROM | disk | FTP | other *** search
- ------------- Listing 2: The file filebuf.c ------------------
-
- // filebuf -- filebuf basic members
- #include <stdio.h>
- #include <fstream>
-
- filebuf::~filebuf()
- { // destruct a filebuf
- if (_Closef)
- close();
- }
-
- filebuf *filebuf::close()
- { // close a file
- if (_File != 0 && fclose(_File) == 0)
- { // note successful close
- _Init();
- return (this);
- }
- else
- return (0);
- }
-
- int filebuf::overflow(int ch)
- { // try to write output
- return (pptr() != 0 && pptr() < epptr()
- ? (*_Pn()++ = ch)
- : _File == 0 ? EOF : ch == EOF ? 0 : fputc(ch, _File));
- }
-
- int filebuf::pbackfail(int ch)
- { // try to pushback a character
- return (gptr() != 0 && eback() < gptr() && ch == gptr()[-1]
- ? *--_Gn()
- : _File == 0 || ch == EOF ? EOF : ungetc(ch, _File));
- }
-
- int filebuf::underflow()
- { // try to peek at input
- return (gptr() != 0 && gptr() < egptr()
- ? *_Gn()
- : _File == 0 ? EOF : ungetc(fgetc(_File), _File));
- }
-
- int filebuf::uflow()
- { // try to consume input
- return (gptr() != 0 && gptr() < egptr()
- ? *_Gn()++
- : _File == 0 ? EOF : fgetc(_File));
- }
-
- streamsize filebuf::xsgetn(char *s, streamsize n)
- { // read n characters
- return (_File == 0 ? 0 : fread(s, 1, n, _File));
- }
-
- streamsize filebuf::xsputn(const char *s, streamsize n)
- { // write n characters
- return (_File == 0 ? 0 : fwrite(s, 1, n, _File));
- }
-
- streampos filebuf::seekoff(streamoff off, ios::seekdir way,
- ios::openmode)
- { // seek by specified offset
- return (streampos(_File == 0
- || fseek(_File, off, way) != 0
- ? _BADOFF : streamoff(ftell(_File))));
- }
-
- streampos filebuf::seekpos(streampos sp, ios::openmode)
- { // seek to memorized position
- return (_File == 0 || fsetpos(_File, sp._Fpos()) != 0
- || fseek(_File, sp.offset(), SEEK_CUR) != 0
- || fgetpos(_File, sp._Fpos()) != 0
- ? streampos(_BADOFF)
- : streampos(0, sp._Fpos()));
- }
-
- streambuf *filebuf::setbuf(char *s, streamsize n)
- { // provide a file buffer
- return (_File == 0 || setvbuf(_File, s, _IOFBF, n) != 0
- ? 0 : this);
- }
-
- int filebuf::sync()
- { // synchronize buffer with file
- return (_File == 0 ? 0 : fflush(_File));
- }
-
- FILE *filebuf::_Init(FILE *fp, bool closef)
- { // initialize buffer pointers
- #if _HAS_PJP_CLIB
- if (fp == 0)
- streambuf::_Init();
- else
- streambuf::_Init((char **)&fp->_Buf,
- (char **)&fp->_Next,
- (char **)&fp->_Rend,
- (char **)&fp->_Buf,
- (char **)&fp->_Next,
- (char **)&fp->_Wend);
- #else
- streambuf::_Init();
- #endif
- _Closef = closef;
- _File = fp;
- return (_File);
- }
-